package com.dykj.fireFighting.web.bigdata;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dykj.fireFighting.api.base.bigdata.device.entity.Device;
import com.dykj.fireFighting.api.base.bigdata.device.service.IDeviceService;
import com.dykj.fireFighting.api.base.dev.entity.DevHisWater;
import com.dykj.fireFighting.api.base.dev.entity.DevHisZc;
import com.dykj.fireFighting.api.base.dev.entity.vo.FireVo;
import com.dykj.fireFighting.api.base.dev.service.IDevHisService;
import com.dykj.fireFighting.api.base.dev.service.IDevHisWaterService;
import com.dykj.fireFighting.api.base.dev.service.IDevHisZcService;
import com.dykj.fireFighting.api.base.devHisResult.entity.DevHisResult;
import com.dykj.fireFighting.api.base.devHisResult.service.IDevHisResultService;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.exception.BaseException;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.utils.ZcDataCleaning;
import com.dykj.fireFighting.common.starter.redisson.service.RedisService;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 社会单位大数据接口
 *
 * @Author LIJIANJIE
 */
@EnableScheduling
@Slf4j
@Api(value = "社会单位大数据接口", tags = {"社会单位大数据接口"})
@RestController
@RequestMapping("/bigData3")
public class BigDataController {

    /**
     * 火警记录
     */
    @DubboReference
    private IDevHisService devHisService;
    /**
     * 电气记录
     */
    @DubboReference
    private IDevHisZcService devHisZcService;
    /**
     * 水警记录
     */
    @DubboReference
    private IDevHisWaterService devHisWaterService;
    /**
     * 设备
     */
    @DubboReference
    private IDeviceService deviceService;
    @Autowired
    private RedisService redisService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 统计
     */
    @DubboReference
    private IDevHisResultService devHisResultService;

    @DubboReference
    private IEnterpriseService enterpriseService;

    /**
     * 获取登录用户的单位id
     */
    public Long getEnterpriseId() {
        try {
            Long enterpriseId = ShiroUtil.getUser().getEnterpriseId();
            return enterpriseId;
        }catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("请登录");
        }
    }

    /**
     * 实时报警（火警、预警、故障）
     */
    @AutoLog(value = "实时报警")
    @ApiOperation(value = "实时报警", notes = "实时报警")
    @RequestMapping(value = "/alarm", method = RequestMethod.GET)
    public CommonResult getAlarm(String beginTime,String endTime) {
        Long enterpriseId = getEnterpriseId();
        Map<String, Integer> map = new HashMap<>(10);
        if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            DevHisResult unitNum = devHisResultService.getUnitNum(enterpriseId + "", beginTime, endTime);
            if (unitNum == null) {
                // 封装
                map.put("fireNum", 0);
                map.put("warnNum", 0);
                map.put("faultNum",0);
                return CommonResult.success(map);
            }else {
                // 封装
                map.put("fireNum", unitNum.getFireAlarm());
                map.put("warnNum", unitNum.getEarlyWarning());
                map.put("faultNum",unitNum.getFault());
                return CommonResult.success(map);
            }
        }else {
            DevHisResult unitNum = devHisResultService.getUnitNum(enterpriseId + "", null, null);
            if (unitNum == null) {
                // 封装
                map.put("fireNum", 0);
                map.put("warnNum", 0);
                map.put("faultNum",0);
                return CommonResult.success(map);
            }else {
                // 封装
                map.put("fireNum", unitNum.getFireAlarm());
                map.put("warnNum", unitNum.getEarlyWarning());
                map.put("faultNum",unitNum.getFault());
                return CommonResult.success(map);
            }
         }
    }

    /**
     * 电气火灾监控
     */
    @AutoLog(value = "电气火灾监控")
    @ApiOperation(value = "电气火灾监控", notes = "电气火灾监控")
    @RequestMapping(value = "/electric", method = RequestMethod.GET)
    public CommonResult getElectric(String relationId) {
        DevHisZc devHisZc=null;
        String str = (String) redisService.get(relationId+"_realtime");
        if(StringUtils.isNotBlank(str)){
            JSONObject jsonMsg = JSON.parseObject(str);
            //devHisZc = (DevHisZc)JSONObject.toJavaObject(jsonMsg, DevHisZc.class);
            devHisZc=JSON.parseObject(str, DevHisZc.class);
            Object bjzt=jsonMsg.get("bjzt");
            if(null!=bjzt){
                devHisZc.setStatus(ZcDataCleaning.dataCleaning(bjzt.toString()));
                devHisZc.setBjztSm(ZcDataCleaning.dataCleaning(bjzt.toString()));
            }

        }
        /*DevHisZc devHisZc = devHisZcService.getElectricLimit(relationId);
        if(null != devHisZc){
            devHisZc.setBjztSm(ZcDataCleaning.dataCleaning(devHisZc.getBjzt()));
        }*/
        return CommonResult.success(devHisZc);
    }

    /**
     * 水压水位监控
     */
    @AutoLog(value = "水压水位监控")
    @ApiOperation(value = "水压水位监控", notes = "水压水位监控")
    @RequestMapping(value = "/water", method = RequestMethod.GET)
    public CommonResult getWater(String relationId) {
        DevHisWater devHisWater = devHisWaterService.getWaterLimit(relationId);
        return CommonResult.success(devHisWater);
    }

    /**
     * 获取设备列表
     * @param type
     * @return
     */
    @AutoLog(value = "获取设备列表")
    @ApiOperation(value = "获取设备列表",notes = "获取设备列表")
    @RequestMapping(value = "/device", method = RequestMethod.GET)
    public CommonResult getDevice(String type) {
        Long enterpriseId = getEnterpriseId();
        List<Device> list = deviceService.getSelect(enterpriseId + "", type);
        return CommonResult.success(list);
    }

    /**
     * 最新报警列表
     * @return
     */
    @AutoLog(value = "最新报警列表")
    @ApiOperation(value = "最新报警列表", notes = "最新报警列表")
    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public CommonResult getNewList(Integer read) {
        Long enterpriseId = getEnterpriseId();
        // 动态表名
        String his = "dev_his_" + DateUtil.getYearWeek();

        List<FireVo> list = devHisService.getNewList(his,enterpriseId + "", read);
        return CommonResult.success(list);
    }

    /**
     * 校验数据
     */
    @Scheduled(cron = "0 0 0,1 * * ?")
    public void checkData() throws ParseException {
        RLock rLock = redissonClient.getLock("result");
        rLock.lock();

        Date date=new Date();
        Date newDate = DateUtil.getNewDate(date, -1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        // 昨天日期
        String upDateStr  = formatter.format(newDate);
        String beginDate = upDateStr + " 00:00:00";
        String endDate = upDateStr + " 23:59:59";

        // 获取年周
        String yearWeek = (UUIDUtils.createYearWeekYes(upDateStr)).substring(0,6);
        // 动态表名
        String his = "dev_his_" + yearWeek;
        String waters = "dev_his_water_" + yearWeek;
        String zc = "dev_his_zc_" + yearWeek;

        // 获取所有单位
        List<Enterprise> allSocialUnit = enterpriseService.getAllSocialUnit();
        for (Enterprise unit : allSocialUnit) {
            // 今天新增初始数据
            DevHisResult devHisResult = new DevHisResult();
            // 获取监控中心
            if (unit.getBindingCode() != null) {
                Enterprise center = enterpriseService.getInfoByBindingCode(unit.getBindingCode());
                if (center != null) {
                    devHisResult.setCenterUnitId(center.getId() + "");
                }
            }
            devHisResult.setId(UUIDUtils.get32UUID());
            devHisResult.setUnitId(unit.getId() + "");
            devHisResult.setResultDate(formatter.parse(DateUtil.getDate()));

            List<DevHisResult> list = devHisResultService.getByUnitId(devHisResult.getUnitId(), devHisResult.getCenterUnitId());
            if (list == null || list.size() == 0) {
                devHisResultService.save(devHisResult);
                System.out.println("插入了一条数据:" + devHisResult.getUnitId());
            }
            try {
            //获取昨天统计数据
            DevHisResult unitNum = devHisResultService.getByTime(upDateStr,unit.getId() + "" );
            // 火警
            int fire = devHisService.getUnitNum(unit.getId()+"",beginDate,endDate, his);
            // 预警
            int water = devHisWaterService.getWaterByTime(unit.getId()+"",beginDate,endDate, waters);
            int ele = devHisZcService.getEleByTime(unit.getId()+"",beginDate,endDate,zc);
            int warn = water + ele;
            // 故障
            int fault = devHisService.countFaultByTime(unit.getId()+"",beginDate,endDate,his);
            // 更新
            if (unitNum != null) {
                unitNum.setFireAlarm(fire);
                unitNum.setFault(fault);
                unitNum.setEarlyWarning(warn);
                devHisResultService.updateById(unitNum);
                System.out.println("修改了一条数据：" + unitNum.getUnitId());
            }
            Thread.sleep(1000);
            }catch (Exception e) {
                System.out.println("数据校验失败---"+e.toString());
            }
        }
        rLock.unlock();
    }

    /*public static void main(String[] args) {
        Date date=new Date();
        Date newDate = DateUtil.getNewDate(date, -1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        // 昨天日期
        String upDateStr  = "2022-03-06";
        System.out.println(upDateStr);
        System.out.println(UUIDUtils.createYearWeekYes(upDateStr).substring(0,6));
    }*/

}
